package hotel.switchs.oversea.online.service.impl;

import hotel.base.oversea.constant.CommonConstants;
import hotel.base.oversea.constant.CommonUrlConstants;
import hotel.base.oversea.constant.enums.SwitchChannelNameEnums;
import hotel.base.oversea.entity.SwitchPriceBaseSetEntity;
import hotel.base.oversea.service.impl.BaseServiceImpl;
import hotel.base.oversea.utils.Result;
import hotel.base.oversea.utils.StringUtil;
import hotel.switchs.oversea.api.entity.SwitchHotelPriceSetRelationEntity;
import hotel.switchs.oversea.api.entity.SwitchHotelPriceSetRelationLogEntity;
import hotel.switchs.oversea.online.config.service.RedisService;
import hotel.switchs.oversea.online.mapper.SwitchHotelPriceSetRelationLogMapper;
import hotel.switchs.oversea.online.mapper.SwitchHotelPriceSetRelationMapper;
import hotel.switchs.oversea.online.mapper.SwitchPriceBaseSetMapper;
import hotel.switchs.oversea.online.service.SwitchPriceBaseSetService;
import hotel.switchs.oversea.online.service.SwitchPushRoomService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author lmf
 * @Date 2020/9/10 16:03
 **/
@Service
@Slf4j
public class SwitchPriceBaseSetServiceImpl extends BaseServiceImpl<SwitchPriceBaseSetEntity> implements SwitchPriceBaseSetService {
    @Autowired
    SwitchPriceBaseSetMapper switchPriceBaseSetMapper;
    @Autowired
    SwitchPushRoomService switchPushRoomService;
    @Autowired
    RedisService redisService;

    @Autowired
    SwitchHotelPriceSetRelationMapper switchHotelPriceSetRelationMapper;

    @Autowired
    SwitchHotelPriceSetRelationLogMapper switchHotelPriceSetRelationLogMapper;

    @Autowired
    SwitchRestTempaleUtilsService switchRestTempaleUtilsService;
    /**
     * @author: lmf
     * @date: 2020/9/10 16:05
     * 添加价格公式
     */
    @Override
    public Result<Object> addPriceBaseSet(SwitchPriceBaseSetEntity switchPriceBaseSetEntity) {
        int result=switchPriceBaseSetMapper.insert(switchPriceBaseSetEntity);
        String key="switch_online_price_sets_up_by_"+ SwitchChannelNameEnums.CTRIP.getName();
        String qunarKey="switch_online_price_sets_up_by_"+SwitchChannelNameEnums.QUNAR.getName();
        if(result>0){
            //如果是默认公式才需要加入缓存
            if(switchPriceBaseSetEntity.getFormula()==0){
                redisService.set(key,switchPriceBaseSetEntity);
                redisService.set(qunarKey,switchPriceBaseSetEntity);
            }else{
                SwitchPriceBaseSetEntity switchPriceBaseSetEntity1=switchPriceBaseSetMapper.selectOne(switchPriceBaseSetEntity);
                List<Integer> hotelId=switchHotelPriceSetRelationMapper.selectHotelListForFormula(switchPriceBaseSetEntity.getFormula());
                if(!ObjectUtils.isEmpty(hotelId)&&hotelId.size()>0){
                    ExecutorService executorService = Executors.newFixedThreadPool(1);
                    executorService.execute(new SwitchAddFormulaThread(hotelId,switchPriceBaseSetEntity1.getId(),switchPriceBaseSetEntity.getFormula()));
                    executorService.shutdown();
                }
            }
            return new Result<>(CommonConstants.SUCCESS,"添加成功");
        }else{
            return new Result<>("添加失败");
        }
    }
    class SwitchAddFormulaThread implements Runnable{
        private List<Integer> hotelIds;
        private Integer sid;
        private Integer formula;
        public SwitchAddFormulaThread(List<Integer> hotelIds, Integer sid, Integer formula) {
            this.hotelIds = hotelIds;
            this.sid = sid;
            this.formula = formula;
        }
        @Override
        public void run() {
            List<SwitchHotelPriceSetRelationLogEntity> switchHotelPriceSetRelationLogEntities=new ArrayList<>();
            for(Integer hotelId:hotelIds){
                SwitchHotelPriceSetRelationEntity switchHotelPriceSetRelationEntity=new SwitchHotelPriceSetRelationEntity();
                switchHotelPriceSetRelationEntity.setHotelId(hotelId);
                switchHotelPriceSetRelationEntity.setSid(this.sid);
                SwitchHotelPriceSetRelationEntity switchHotelPriceSetRelationEntity1=switchHotelPriceSetRelationMapper.selectOne(switchHotelPriceSetRelationEntity);
                if(!ObjectUtils.isEmpty(switchHotelPriceSetRelationEntity1)){
                    continue;
                }
                switchHotelPriceSetRelationEntity.setFormula(this.formula);
                switchHotelPriceSetRelationEntity.setCreateTime(new Date());
                switchHotelPriceSetRelationEntity.setHotelId(hotelId);
                switchHotelPriceSetRelationEntity.setId(StringUtil.getUUID());
                switchHotelPriceSetRelationEntity.setModifyTime(new Date());
                switchHotelPriceSetRelationEntity.setSid(this.sid);
                SwitchHotelPriceSetRelationLogEntity switchHotelPriceSetRelationLogEntity=new SwitchHotelPriceSetRelationLogEntity();
                switchHotelPriceSetRelationLogEntity.setCreateTime(new Date());
                switchHotelPriceSetRelationLogEntity.setHotelId(hotelId);
                switchHotelPriceSetRelationLogEntity.setId(StringUtil.getUUID());
                switchHotelPriceSetRelationLogEntity.setModifyTime(new Date());
                switchHotelPriceSetRelationLogEntity.setFormula(this.formula);
                switchHotelPriceSetRelationLogEntity.setRemark("");
                switchHotelPriceSetRelationLogEntity.setSid(this.sid);
                switchHotelPriceSetRelationLogEntities.add(switchHotelPriceSetRelationLogEntity);
                int flag=switchHotelPriceSetRelationMapper.insert(switchHotelPriceSetRelationEntity);
               /* if(flag>0){
                    String keys=CommonConstants.SWITCH_HOTEL_PRICE_SET_RELATION;
                    redisService.hmDel(keys,hotelId+ SwitchChannelNameEnums.CTRIP.getName());
                    redisService.hmDel(keys,hotelId+ SwitchChannelNameEnums.QUNAR.getName());
                }*/
            }
            if(switchHotelPriceSetRelationLogEntities.size()>0){
                switchHotelPriceSetRelationLogMapper.insertList(switchHotelPriceSetRelationLogEntities);
            }
            redisService.remove(CommonConstants.SWITCH_HOTEL_PRICE_SET_RELATION);
        }
    }
    /***
     * @Author: lmf
     * @Date: 2021/3/4
     * 价格时间公式分割点
     */
    @Override
    public Result<Object> setPriceTimeToCache(Integer hour) {
        log.info("===========修改定时任务的crontab========");
        Map<String,String> params=new HashMap<>();
        params.put("jobClassName","hotel.quartz.job.callback.MtCbGoodsRedisRemoveJob");
        params.put("jobGroupName","Callback");
        params.put("cronExpression","00 00 3,"+hour+" * * ?");
        String url= CommonUrlConstants.GATE_WAY_HOST+"/api/quartz/job/cronJob";
        log.info("======url的值为{}=====",url);
        Result<Object> result = switchRestTempaleUtilsService.sendPutToQuartModifyCrontab(url, params);
        log.info("=========修改定時任務的返回值为{}======",result);
        redisService.set(CommonConstants.SWITCH_PRICE_SET_PRICE_TIME,hour);
        //删除缓存
        String key="switch_online_price_sets_up_by_"+ SwitchChannelNameEnums.CTRIP.getName();
        String qunarKey="switch_online_price_sets_up_by_"+SwitchChannelNameEnums.QUNAR.getName();
        if(redisService.exists(key)){
            redisService.remove(key);
        }
        if(redisService.exists(qunarKey)){
            redisService.remove(qunarKey);
        }
        List<SwitchPriceBaseSetEntity> switchPriceBaseSetEntities=switchPriceBaseSetMapper.selectAll();
        for(SwitchPriceBaseSetEntity switchPriceBaseSetEntity:switchPriceBaseSetEntities){
            ExecutorService executorService = Executors.newFixedThreadPool(1);
            executorService.execute(new SwitchRemoveFormualThread(switchPriceBaseSetEntity.getId()));
            executorService.shutdown();
        }
        return new Result<>();
    }
    /***
     * @Author: lmf
     * @Date: 2021/3/4
     * 控制酒店是否执行自已的价格公式
     */
    @Override
    public Result<Object> setOpenHotelPriceToCache(Integer open) {
        if(open==1){
            redisService.set(CommonConstants.SWITCH_IS_OPEN_HOTEL_OWNER_PRICE_FORMULA,1);
        }else{
            redisService.remove(CommonConstants.SWITCH_IS_OPEN_HOTEL_OWNER_PRICE_FORMULA);
        }
        return new Result<>();
    }


    /**
     * @author: lmf
     * @date: 2020/9/10 16:43
     * 获取价格公式列表
     */
    @Override
    public Result<Object> getPriceList() {
        Integer hour=18;
        if(redisService.exists(CommonConstants.SWITCH_PRICE_SET_PRICE_TIME)){
            hour= (Integer) redisService.get(CommonConstants.SWITCH_PRICE_SET_PRICE_TIME);
        }
        String open="0";
        if(redisService.exists(CommonConstants.SWITCH_IS_OPEN_HOTEL_OWNER_PRICE_FORMULA)){
            open="1";
        }
        List<SwitchPriceBaseSetEntity> list=switchPriceBaseSetMapper.getList();
        Map<String,Object> response=new HashMap<>();
        response.put("list",list);
        response.put("hour",hour);
        response.put("open",open);
        return new Result<>(response);
    }
    /**
     * @author: lmf
     * @date: 2020/9/10 17:57
     * 根据id上架价格配置
     */
    @Override
    public Result<Object> deletePriceListById(int id) {
        SwitchPriceBaseSetEntity switchPriceBaseSetEntity=new SwitchPriceBaseSetEntity();
        switchPriceBaseSetEntity.setId(id);
        SwitchPriceBaseSetEntity switchPriceBaseSetEntitys=switchPriceBaseSetMapper.selectOne(switchPriceBaseSetEntity);
        if(ObjectUtils.isEmpty(switchPriceBaseSetEntitys)){
            return new Result<>("找不到此条数据");
        }
        int result=switchPriceBaseSetMapper.delete(switchPriceBaseSetEntity);
        String key="switch_online_price_sets_up_by_"+ SwitchChannelNameEnums.CTRIP.getName();
        String qunarKey="switch_online_price_sets_up_by_"+SwitchChannelNameEnums.QUNAR.getName();
        if(result>0){
            if(switchPriceBaseSetEntitys.getFormula()==0){
                redisService.remove(key);
                redisService.remove(qunarKey);
            }else{
                ExecutorService executorService = Executors.newFixedThreadPool(1);
                executorService.execute(new SwitchRemoveFormualThreadAndLog(id));
                executorService.shutdown();
            }
            return new Result<>(CommonConstants.SUCCESS,"删除成功");
        }else{
            return new Result<>("删除失败");
        }
    }
    /**
     * @author: lmf
     * @date: 2020/9/10 17:59
     * 根据id上架价格公式
     */
    @Override
    public Result<Object> updatePriceListById(SwitchPriceBaseSetEntity switchPriceBaseSetEntity) {
        SwitchPriceBaseSetEntity switchPriceBaseSetEntity1=new SwitchPriceBaseSetEntity();
        switchPriceBaseSetEntity1.setId(switchPriceBaseSetEntity.getId());
        SwitchPriceBaseSetEntity switchPriceBaseSetEntitys=switchPriceBaseSetMapper.selectOne(switchPriceBaseSetEntity1);
        if(ObjectUtils.isEmpty(switchPriceBaseSetEntitys)){
            return new Result<>("找不到此条数据");
        }
        int result=switchPriceBaseSetMapper.updateById(switchPriceBaseSetEntity);
        String key="switch_online_price_sets_up_by_"+ SwitchChannelNameEnums.CTRIP.getName();
        String qunarKey="switch_online_price_sets_up_by_"+SwitchChannelNameEnums.QUNAR.getName();
        if(result>0){
            //如果是默认公式才需要清除缓存
            if(switchPriceBaseSetEntitys.getFormula()==0){
                redisService.remove(key);
                redisService.remove(qunarKey);
            }else{
                ExecutorService executorService = Executors.newFixedThreadPool(1);
                executorService.execute( new SwitchRemoveFormualThread(switchPriceBaseSetEntity.getId()));
                executorService.shutdown();
            }
            return new Result<>(CommonConstants.SUCCESS,"更新成功");
        }else{
            return new Result<>("更新失败");
        }
    }

    /***
     * @Author: lmf
     * @Date: 2021/3/3
     * 清除缓存
     */
    class SwitchRemoveFormualThread implements Runnable{
        private Integer id;

        public SwitchRemoveFormualThread(Integer id) {
            this.id = id;
        }
        @Override
        public void run() {
            //如果是二类或者三类要删除缓存
            Example example=new Example(SwitchHotelPriceSetRelationEntity.class);
            Example.Criteria criteria=example.createCriteria();
            criteria.andEqualTo("sid",this.id);
            List<SwitchHotelPriceSetRelationEntity>  switchHotelPriceSetRelationEntities=switchHotelPriceSetRelationMapper.selectByExample(example);
            if(!ObjectUtils.isEmpty(switchHotelPriceSetRelationEntities)&&switchHotelPriceSetRelationEntities.size()>0){
                for(SwitchHotelPriceSetRelationEntity switchHotelPriceSetRelationEntity:switchHotelPriceSetRelationEntities){
                    String keys=CommonConstants.SWITCH_HOTEL_PRICE_SET_RELATION;
                    redisService.hmDel(keys,switchHotelPriceSetRelationEntity.getHotelId()+ SwitchChannelNameEnums.CTRIP.getName());
                    redisService.hmDel(keys,switchHotelPriceSetRelationEntity.getHotelId()+ SwitchChannelNameEnums.QUNAR.getName());
                }
            }
            redisService.remove(CommonConstants.SWITCH_HOTEL_PRICE_SET_RELATION);
        }
    }

    /***
     * @Author: lmf
     * @Date: 2021/3/3
     * 清除缓存
     */
    class SwitchRemoveFormualThreadAndLog implements Runnable{
        private Integer id;

        public SwitchRemoveFormualThreadAndLog(Integer id) {
            this.id = id;
        }
        @Override
        public void run() {
            //如果是二类或者三类要删除记录和缓存
            Example example=new Example(SwitchHotelPriceSetRelationEntity.class);
            Example.Criteria criteria=example.createCriteria();
            criteria.andEqualTo("sid",this.id);
            List<SwitchHotelPriceSetRelationEntity>  switchHotelPriceSetRelationEntities=switchHotelPriceSetRelationMapper.selectByExample(example);
            if(!ObjectUtils.isEmpty(switchHotelPriceSetRelationEntities)&&switchHotelPriceSetRelationEntities.size()>0){
                for(SwitchHotelPriceSetRelationEntity switchHotelPriceSetRelationEntity:switchHotelPriceSetRelationEntities){
                    String keys=CommonConstants.SWITCH_HOTEL_PRICE_SET_RELATION;
                    criteria.andEqualTo("hotelId",switchHotelPriceSetRelationEntity.getHotelId());
                    int flag=switchHotelPriceSetRelationMapper.deleteByExample(example);
                    if(flag>0){
                        redisService.hmDel(keys,switchHotelPriceSetRelationEntity.getHotelId()+ SwitchChannelNameEnums.CTRIP.getName());
                        redisService.hmDel(keys,switchHotelPriceSetRelationEntity.getHotelId()+ SwitchChannelNameEnums.QUNAR.getName());
                    }
                }
            }
            redisService.remove(CommonConstants.SWITCH_HOTEL_PRICE_SET_RELATION);
        }
    }

    /***
     * @Author: lmf
     * @Date: 2021/3/8
     * 获取酒店当前使用的价格公式列表
     */
    @Override
    public Result<Object> getPriceRelationList(Integer hotelId) {
        int day=0;
        if(redisService.exists(CommonConstants.SWITCH_PRICE_SET_PRICE_TIME)){
            Integer time= (Integer) redisService.get(CommonConstants.SWITCH_PRICE_SET_PRICE_TIME);
            Calendar calendar=Calendar.getInstance();
            int hour=calendar.get(Calendar.HOUR_OF_DAY);
            if(hour>=time){
                day=1;
            }
        }
        List<SwitchPriceBaseSetEntity> switchPriceBaseSetEntities=switchPriceBaseSetMapper.selectByChannelNameAndDay(SwitchChannelNameEnums.CTRIP.getName(),day);;
        if(redisService.exists(CommonConstants.SWITCH_IS_OPEN_HOTEL_OWNER_PRICE_FORMULA)){
            //获取酒店是否有自已独立的价格公式
            List<SwitchPriceBaseSetEntity> switchPriceBaseSetEntities2=switchPriceBaseSetMapper.selectByChannelNameAndHotelRelation(hotelId,SwitchChannelNameEnums.CTRIP.getName(),day);
            if(!ObjectUtils.isEmpty(switchPriceBaseSetEntities2)&&switchPriceBaseSetEntities2.size()>0){
                switchPriceBaseSetEntities=switchPriceBaseSetEntities2;
            }
        }
        return new Result<>(switchPriceBaseSetEntities);
    }

    /***
     * @Author: lmf
     * @Date: 2021/4/15
     * 调整价格公式
     */
    @Override
    public Result<Object> adjustHotelPirceFormula(Integer genre) {
        //开启月初佣金调整
        if(redisService.exists(CommonConstants.SWITCH_CONTROL_IS_OPEN_ADJUST_HOTEL_PRICE_FORMULA)){
            if(genre==0){//调低价格  2%
                List<SwitchPriceBaseSetEntity> switchPriceBaseSetEntities=switchPriceBaseSetMapper.selectAll();
                switchPriceBaseSetEntities.forEach(e->{
                    BigDecimal bigDecimal=e.getRate();
                    double rate=bigDecimal.doubleValue()-2;
                    int result=switchPriceBaseSetMapper.updateFormulaById(e.getId(),rate);
                    String key="switch_online_price_sets_up_by_"+ SwitchChannelNameEnums.CTRIP.getName();
                    String qunarKey="switch_online_price_sets_up_by_"+SwitchChannelNameEnums.QUNAR.getName();
                    if(result>0){
                        //如果是默认公式才需要清除缓存
                        if(e.getFormula()==0){
                            redisService.remove(key);
                            redisService.remove(qunarKey);
                        }else{
                            ExecutorService executorService = Executors.newFixedThreadPool(1);
                            executorService.execute( new SwitchRemoveFormualThread(e.getId()));
                            executorService.shutdown();
                        }
                    }
                });
            }else{//调高价格
                List<SwitchPriceBaseSetEntity> switchPriceBaseSetEntities=switchPriceBaseSetMapper.selectAll();
                switchPriceBaseSetEntities.forEach(e->{
                    BigDecimal bigDecimal=e.getRate();
                    double rate=bigDecimal.doubleValue()+2;
                    int result=switchPriceBaseSetMapper.updateFormulaById(e.getId(),rate);
                    String key="switch_online_price_sets_up_by_"+ SwitchChannelNameEnums.CTRIP.getName();
                    String qunarKey="switch_online_price_sets_up_by_"+SwitchChannelNameEnums.QUNAR.getName();
                    if(result>0){
                        //如果是默认公式才需要清除缓存
                        if(e.getFormula()==0){
                            redisService.remove(key);
                            redisService.remove(qunarKey);
                        }else{
                            ExecutorService executorService = Executors.newFixedThreadPool(1);
                            executorService.execute( new SwitchRemoveFormualThread(e.getId()));
                            executorService.shutdown();
                        }
                    }
                });
            }
        }
        return new Result<>();
    }
}
